package q1.project.core.config;

import java.util.EnumSet;
import java.util.UUID;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.generator.BeforeExecutionGenerator;
import org.hibernate.generator.EventType;
import org.springframework.util.ObjectUtils;
import q1.project.core.entity.BaseEntity;

/**
 * Hibernate 6.5+ identifier generator that reuses an existing ID when provided,
 * otherwise emits a lowercase, dashless UUID string.
 *
 * @author sun
 * @date 2025/11/28 00:37
 */
public class IdGeneratorConfig implements BeforeExecutionGenerator {

  @Override
  public EnumSet<EventType> getEventTypes() {
    return EnumSet.of(EventType.INSERT);
  }

  @Override
  public Object generate(
      SharedSessionContractImplementor session,
      Object entity,
      Object currentValue,
      EventType eventType) {

    if (entity instanceof BaseEntity baseEntity && !ObjectUtils.isEmpty(baseEntity.getId())) {
      return baseEntity.getId();
    }

    return UUID.randomUUID().toString().replace("-", "").toLowerCase();
  }
}
